#!/bin/bash
# cJSON 编译脚本(支持交叉编译)
# Optional Command Arguments:
#    ONLYBUILD   不执行 cmake 创建工程只编译版本
#	 BUILD_UTILS build cjson utils
#	 BUILD_TEST  build test
# Optional Environment Variables: 
#    TOOLCHAIN_FILE 指定交叉编译的工具链文件
# 	 MACHINE 目标平台, such as x86_64-linux-gnu,默认使用当前系统平台
#    PREFIX 安装路径
#    PROJECT_FOLDER cmake 生成的工程文件(Makefile)文件夹
#    BUILD_TYPE 编译版本类型(DEBUG|RELEASE),默认 RELEASE

#字符串转大写
#参数：1字符串
function string_toupper()
{
    echo $1 | tr '[a-z]' '[A-Z]'
}
sh_folder=$(cd "$(dirname $0)"; pwd -P)
folder_name=$(basename $sh_folder) 
# 定义编译的版本类型(DEBUG|RELEASE)
build_type=RELEASE
[[ "$(string_toupper $BUILD_TYPE)" =~ DEBUG|RELEASE ]] && build_type=$(string_toupper ${BUILD_TYPE})

echo build_type=$build_type

# 执行 cmake 创建工程
create_prj=ON
build_utils=OFF
build_test=OFF
while [[ $# -gt 0 ]]
do
# 转大写
key=$(string_toupper ${1})
case $key in
ONLYBUILD)
	create_prj=OFF;shift;;
BUILD_UTILS)
	build_utils=ON;shift;;
BUILD_TEST)
	build_test=ON;shift;;
*) echo INVALID ARGUMENT $key;exit 255;shift;;
esac
done

machine=$(g++ -dumpmachine)

[ -n "$MACHINE" ] && machine=$MACHINE

# 工具链文件
toolchain=
[ -n "$TOOLCHAIN_FILE" ] && toolchain="-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE"

# 安装路径
[ -n "$PREFIX" ] && install_prefix="$PREFIX"
[ -z "$PREFIX" ] && install_prefix=$sh_folder/release/cJSON-$machine

# 编译路径
[ -n "$PROJECT_FOLDER" ] && prj_folder="$PROJECT_FOLDER"
[ -z "$PROJECT_FOLDER" ] && prj_folder=$sh_folder/build/cJSON-$machine

echo =========================================================================
echo       Configuration: cJSON $machine:$build_type
echo     Build Directory: $prj_folder
echo   Install Directory: $install_prefix
echo =========================================================================

if [[ "${create_prj}" = ON ]]
then
	[ -d $prj_folder ] && rm -fr $prj_folder
	mkdir -p $prj_folder || exit 

	pushd $prj_folder || exit
	echo "creating Project for $machine ..."
	cmake "$sh_folder/cJSON" -G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_BUILD_TYPE=$build_type \
		-DCMAKE_INSTALL_PREFIX=$install_prefix \
		-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
		-DBUILD_SHARED_AND_STATIC_LIBS=ON \
		-DENABLE_CJSON_UTILS=$build_utils \
		-DENABLE_CJSON_TEST=$build_test \
		-DCMAKE_DEBUG_POSTFIX=_d \
		-DENABLE_TARGET_EXPORT=ON \
		-DENABLE_CUSTOM_COMPILER_FLAGS=OFF \
		$toolchain || exit

else
	pushd $prj_folder || exit
fi

cmake --build . --target install/strip -- -j8 || exit 

popd

